<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <div class="searchBox">
            <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="采购计划编码">
                    <el-input v-model="queryParams.aCode" placeholder="请输入采购计划编码"></el-input>
                </el-form-item>
                <el-form-item label="采购业务类型">
                    <el-select v-model="queryParams.typeId" placeholder="请选择业务类型">
                        <el-option v-for="dict in dict.type.business_type" :label="dict.label" :value="dict.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="采购计划名称">
                    <el-input v-model="queryParams.aName" placeholder="请输入采购计划名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onInsert">新建</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onRest">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 采购计划状态区域 -->
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
            <el-menu-item index="1">待提交</el-menu-item>
            <el-menu-item index="2">待审批</el-menu-item>
            <el-menu-item index="3">已生效</el-menu-item>
        </el-menu>
        <!-- 主要内容 -->
        <div class="contentForm">
            <el-table key="waitSubmit" :data="planList" v-loading="planLoading"
                v-if="activeIndex === '1' || activeIndex === '3'">
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column fixed prop="aId" label="序号" align="center">
                </el-table-column>
                <el-table-column prop="aCode" label="采购计划编号" align="center">
                </el-table-column>
                <el-table-column prop="aName" label="采购计划名称" align="center">
                </el-table-column>
                <el-table-column prop="typeId" label="采购业务类型" align="center" :formatter="typeFormatter">
                </el-table-column>
                <el-table-column prop="projectCount" label="行项目数量" align="center">
                </el-table-column>
                <el-table-column prop="createBy" label="创建人" align="center">
                </el-table-column>
                <el-table-column prop="createTime" label="创建日期" align="center">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button @click="lookPurchasePlan(scope.row)" type="text" size="small">查看</el-button>
                        <el-button type="text" @click="editByACode(scope.row.aCode)" size="small"
                            v-if="activeIndex === '1'">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-table key="waitProcess" border v-loading="loading" :data="processList" v-if="activeIndex === '2'">
                <el-table-column type="expand" label="附件" align="center">
                    <template slot-scope="scope">
                        <el-descriptions border :column="4" direction="vertical">
                            <el-descriptions-item label="附件名称">
                                <p v-for="(i, index) in scope.row.fileList" :key="index">
                                    <a target="_blank" :href="i.url">
                                        {{ i.name }}
                                    </a>
                                </p>
                            </el-descriptions-item>
                        </el-descriptions>
                    </template>
                </el-table-column>
                <el-table-column label="序号" align="center" prop="aid" width="80">
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="采购计划编号" align="center" prop="aCode" />
                <el-table-column label="计划名称" align="center" prop="aName" />
                <el-table-column label="创建部门" align="center" prop="deptId" />
                <el-table-column label="采购业务类型名称" align="center" prop="typeId" :formatter="typeFormatter">
                </el-table-column>
                <el-table-column label="采购审批状态" align="center" prop="aAstate">
                    <template slot-scope="scop">
                        <el-tag size="danger">待审批</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button @click="lookPurchasePlan(scope.row)" type="text" size="small">查看
                        </el-button>
                    </template>
                </el-table-column>

            </el-table>

            <div class="pageArea">
                <div class="pageButton" style="margin-left: auto;">
                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </div>
            </div>
        </div>
        <el-dialog @close="cancel" title="采购计划" :visible.sync="open" width="1000px" append-to-body>
            <el-tabs v-model="paneName" @tab-click="changeAstate">
                <el-tab-pane label="基础资料" name="basic">
                    <el-descriptions direction="vertical" class="margin-top" :column="4" size="medium" border>
                        <el-descriptions-item label="采购计划编号">{{ form.aCode }}</el-descriptions-item>
                        <el-descriptions-item label="计划名称">{{ form.aName }}</el-descriptions-item>
                        <el-descriptions-item label="创建人">{{ form.createBy }}</el-descriptions-item>
                        <el-descriptions-item label="创建部门">{{ form.deptName }}</el-descriptions-item>
                        <el-descriptions-item label="附件">
                            <el-button v-for="(item, index) in file" :key="index" type="primary"
                                @click="downloadMethod(item)">
                                下载 {{ item.name }} <i class="el-icon-download"></i>
                            </el-button>
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-table max-height="250" :data="budgetList" style="margin-top: 20px">
                        <el-table-column fixed height="250" align="center" header-align="center" prop="deptId"
                            label="部门名称" :formatter="deptFormaterH">
                        </el-table-column>
                        <el-table-column prop="duId" align="center" label="预算科目编号">
                        </el-table-column>
                        <el-table-column prop="duName" align="center" label="预算科目名称">
                        </el-table-column>
                        <el-table-column prop="duTotal" align="center" label="总金额">
                        </el-table-column>
                    </el-table>
                    <!-- 行项目 -->
                    <el-table @cell-click="click" max-height="250" v-loading="loading" :data="itemList"
                        style="margin-top: 20px">
                        <el-table-column type="expand">
                            <template slot-scope="props">
                                <el-descriptions border>
                                    <el-descriptions-item label="产品名称">{{ props.row.tName
                                        }}</el-descriptions-item>
                                    <el-descriptions-item label="计量单位">{{ props.row.tUnit
                                        }}</el-descriptions-item>
                                    <el-descriptions-item label="税率">{{ props.row.taxRate
                                        }}</el-descriptions-item>
                                    <el-descriptions-item label="类别">
                                        <el-tag size="small">{{ props.row.cName }}</el-tag>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="需求说明">{{ props.row.tIllustrate }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="规格型号">{{ props.row.tModel }}</el-descriptions-item>
                                </el-descriptions>
                            </template>
                        </el-table-column>
                        <el-table-column label="行项目编号" align="center" prop="vCode" width="160" />
                        <el-table-column label="数量" align="center" prop="vCount" />
                        <el-table-column label="采购人" align="center" prop="vPerson" />
                        <el-table-column label="交付时间" align="center" prop="vDeliveryTime" width="180">
                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.vDeliveryTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="交付地点" align="center" prop="vDeliveryArea" width="150" />
                        <el-table-column label="需求说明" align="center" prop="vIllustrate" />
                    </el-table>


                    <el-card v-if="form.astate != 2" ref="card" style="margin-top: 20px" class="never">
                        <div slot="header" class="clearfix">
                            <span v-if="queryParams.astate == 1">提交意见</span>
                            <span v-if="queryParams.astate == 2">审核意见</span>
                            <el-button @click="item.show = !item.show" style="float: right; padding: 3px 0" type="text">
                                {{ item.show ? '隐藏意见' : '显示意见' }}
                            </el-button>
                        </div>
                        <div v-if="item.show" class="text item">
                            <editor v-model="form.aOpinion" :min-height="120" />
                        </div>
                    </el-card>
                </el-tab-pane>

                <el-tab-pane label="审核记录" name="processed">
                    <el-steps space="200" simple :active="form.planStatus - 1">
                        <el-step title="待提交"></el-step>
                        <el-step title="待审核"></el-step>
                        <el-step title="已生效"></el-step>
                    </el-steps>
                    <el-table style="margin-top: 20px" max-height="250" v-loading="planLoading" :data="planNode">
                        <el-table-column label="序号" align="center" type="index" prop="rid">
                            <!-- <template slot-scope="scope">
                                {{ scope.$index + 1 }}
                            </template> -->
                        </el-table-column>
                        <el-table-column label="创建者" align="center" prop="processedBy" v-if="form.planStatus == 1">
                            <template slot-scope="scope">
                                <span>{{ scope.row.createBy }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核人" align="center" prop="processedBy"
                            v-if="form.planStatus == 2 || form.planStatus == 3">
                            <template slot-scope="scope">
                                <span>{{ scope.row.processedBy }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="处理时间" align="center" prop="pTime"
                            v-if="form.planStatus == 2 || form.planStatus == 3">
                            <template slot-scope="scope">
                                <span>{{ scope.row.pTime }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="创建时间" align="center" prop="createTime" v-if="form.planStatus == 1">
                            <template slot-scope="scope">
                                <span>{{ scope.row.createTime }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="所属部门" align="center" prop="deptName" />
                        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                            <template slot-scope="scope">
                                <span>{{ scope.row.createTime }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <div slot="footer" class="dialog-footer">
                <el-button v-if="queryParams.astate == 1" type="primary" v-loading.fullscreen.lock="fullscreenLoading"
                    @click="sumbitPlan">提 交
                </el-button>

                <div style="display: inline-block;margin-right: 10px" v-if="queryParams.astate == 2">
                    <el-button type="primary" @click="approved" v-loading.fullscreen.lock="fullscreenLoading">审核
                    </el-button>
                    <el-button type="danger" @click="rejectPlan" v-loading.fullscreen.lock="fullscreenLoading">驳回
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getPlanList, getPurchasePlanByACode, getPlanByState, changeAstateByACode, changeAstateByACodeAdmin, getCategory } from '@/api/system/purchase'
import { listDept } from '@/api/system/dept'

export default {
    dicts: ["business_type", "device_type"],
    data() {
        return {
            planNode: [],
            planLoading: true,
            fullscreenLoading: false,
            activeIndex: "1",
            budgetData: [],
            item: {
                show: true
            },
            planLoading: true,//采购计划加载
            form: {
                aCode: null,
                aName: null,
                createBy: null,
                deptId: null,
                deptName: "",//将deptId经过for循环匹配后的文字
                aOpinion: "",
                planStatus: 1,
            },
            file: [],
            planList: [
            ],
            processList: [],//审核采购计划和文件
            props: [],
            itemList: [],//行项目信息
            paneName: 'basic',
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                // 搜索条件
                aCode: null,
                typeId: null,
                aName: null,
                astate: 1,
            },
            budgetList: [],//预算信息
            deptList: [],
            open: false,
            loading: true,
            // 外
            outerVisible: false,
            //内
            innerVisible: false,
            title: '',//弹窗标题
            //分页总条数
            total: 0,
        }
    },
    mounted() {
        this.getDeptList();
        this.handleSelect(this.$route.query.astate)
    },
    methods: {
        //关闭
        cancel() {
            this.open = false
            this.item.show = true;
            setTimeout(() => {
                this.form = {
                    aCode: null,
                    aName: null,
                    createBy: null,
                    deptId: null,
                    deptName: "",//将deptId经过for循环匹配后的文字
                    aOpinion: "",
                }
                this.budgetData = [];
                this.itemList = [];
                this.paneName = "basic";
                this.reset()
            }, 500)
        },
        onSubmit() {
            this.getList();
        },
        onInsert() {
            this.$router.push('/purchase/plan/add');
        },
        onRest() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                // 搜索条件
                aCode: null,
                typeId: null,
                aName: null,
                astate: this.queryParams.astate,
            }
        },
        handleSelect(index) {
            // 处理菜单选择变化的逻辑  
            this.activeIndex = index; // 设置新的激活项  
            this.queryParams.astate = parseInt(index, 10);
            if (index === "1") {
                this.getList();
                this.form.planStatus = 1;
            } else if (index === "2") {
                this.getProcessAndFile();
                this.form.planStatus = 2;
            } else if (index === "3") {
                this.getList();
                this.form.planStatus = 3;
            }

        },
        getList() {
            // 处理查询参数
            this.planLoading = false;
            let params = { ...this.queryParams };
            // 执行查询
            getPlanList(params).then(response => {
                this.planList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        typeFormatter(row, column, cellValue, index) {
            let label = "";
            this.dict.type.business_type.forEach(rse => {
                if (cellValue === Number(rse.value)) {
                    label = rse.label;
                    return;
                }
            })
            return label;
        },
        //单击查看预算
        click(row, column, cell, event) {
            console.log("row", row)
        },
        reset() {
            this.form = {
                aid: null,
                aCode: null,
                aName: null,
                createBy: null,
                aCreateDept: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                fjAnnex: null,
                aOpinion: null,
                aProjectCount: null,
                aBtype: null,
                aAstate: 0,
                editor: ""
            }
        },
        //部门转化(无惨)
        deptFormater() {
            for (let i = 0; i < this.deptList.length; i++) {
                if (this.form.deptId == this.deptList[i].deptId) {
                    this.form.deptName = this.deptList[i].deptName
                }
            }
        },
        //部门转化(有惨)
        deptFormaterH(row, column, cellValue, index) {
            for (let i = 0; i < this.deptList.length; i++) {
                if (cellValue == this.deptList[i].deptId) {
                    return this.deptList[i].deptName;
                }
            }
        },
        //获得部门
        getDeptList() {
            listDept().then(response => {
                this.deptList = response.data; // 将获取的数据赋值给 deptList
            })
        },
        //查看选中采购计划行的信息
        lookPurchasePlan(row) {
            this.selectPurchasePlan(row.aCode);
        },
        //后端跟进采购计划查询行项目信息,预算信息,附件文件
        selectPurchasePlan(aCode) {
            this.open = true;
            this.loading = true;
            getPurchasePlanByACode(aCode).then(res => {
                this.loading = false;
                if (res.msg === "success") {
                    if (res.data && res.data.plan && res.data.plan.fileList != null) {
                        this.file = res.data.plan.fileList; // 文件
                    }
                    this.form = res.data.plan
                    this.deptFormater();//部门
                    this.budgetList = res.data.budgetList;//预suan

                    getCategory().then(response => {
                        const nameMap = Object.fromEntries(response.data.map(ree => [ree.cId, ree.cName]));
                        res.data.deviceList.forEach((ele) => {
                            if (nameMap[ele.cId]) {
                                ele.cName = nameMap[ele.cId];
                            }
                        });
                    })
                    this.itemList = res.data.deviceList;
                    this.planNode = [];
                    this.planNode.push(res.data.plan);
                }
            })
        },
        async downloadMethod(fileInfoL) {
            try {
                // 获取响应
                let response = await fetch(fileInfoL.url);

                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('网络响应失败');
                }

                // 内容转变成blob地址
                let blob = await response.blob();

                // 创建隐藏的可下载链接
                let objectUrl = window.URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.style.display = "none";
                a.href = objectUrl;
                a.download = fileInfoL.name;

                // 触发点击
                document.body.appendChild(a);
                a.click();

                // 移除
                URL.revokeObjectURL(a.href);
                document.body.removeChild(a);
            } catch (error) {
                console.error('下载文件时出错:', error);
            }
        },
        //驳回审核意见
        rejectPlan() {
            if (!this.form.aOpinion) {
                this.$modal.msgError("请输入审核意见")
                return;
            }
            this.$modal.confirm("你确定要驳回采购计划吗？").then(() => {
                this.changeAstateByACode(1);
            })
        },
        //同意
        approved() {
            if (!this.form.aOpinion) {
                this.$modal.msgError("请输入审核意见")
                return;
            }
            this.$modal.confirm("你确定同意采购计划吗？").then(() => {
                this.changeAstateByACode(3);
            })
        },
        getProcessAndFile() {
            getPlanByState(this.queryParams.astate).then(res => {
                this.loading = false;
                this.processList = res.data;
            })
        },
        //更改查询的astate
        changeAstate(active, sleep) {
            switch (active.name) {
                case 'basic':
                    this.getList();
                    break;
                case 'processed':
                    if (this.activeIndex == "1") {
                        this.getList();
                        this.form.planStatus = 1
                    } else if (this.activeIndex == "2") {
                        this.getProcessAndFile();
                        this.form.planStatus = 2
                    } else if (this.activeIndex == "3") {
                        this.getList();
                        this.form.planStatus = 3;
                    }
                    break;
            }
        },
        editByACode(aCode) {
            this.$router.push({ path: '/purchase/plan/edit', query: { aCode: aCode } });
        },
        //提交采购计划
        sumbitPlan() {
            this.$modal.confirm("你确定要提交采购计划吗？").then(() => {
                this.changeAstateByACode(2)
            })
        },
        changeAstateByACode(astate) {
            const form = {
                astate: astate,
                aCode: this.form.aCode,
                aOpinion: this.form.aOpinion
            }
            if (astate == 3 || astate == 1) {
                changeAstateByACodeAdmin(form).then(res => {
                    if (res.data > 0) {
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                        this.cancel();
                        //只包含不等于form.aCode的数据(过滤掉相同的数据,保留不同的数据)
                        if (this.queryParams.astate == 1 || this.queryParams.astate == 3) {
                            this.planList = this.planList.filter(item => item.aCode !== this.form.aCode);
                        } else {
                            this.processList = this.processList.filter(item => item.aCode !== this.form.aCode);
                        }
                    } else {
                        this.$message({
                            message: '提交失败',
                            type: 'error',
                        });
                    }
                })
                return false;
            }
            changeAstateByACode(form).then(res => {
                if (res.data > 0) {
                    this.$message({
                        message: '提交成功',
                        type: 'success'
                    });
                    this.cancel();
                    //只包含不等于form.aCode的数据(过滤掉相同的数据,保留不同的数据)
                    if (this.queryParams.astate == 1 || this.queryParams.astate == 3) {
                        this.planList = this.planList.filter(item => item.aCode !== this.form.aCode);
                    } else {
                        this.processList = this.processList.filter(item => item.aCode !== this.form.aCode);
                    }
                } else {
                    this.$message({
                        message: '提交失败',
                        type: 'error',
                    });
                }
            }).catch(() => {
                this.$modal.msgError("服务器出错，请联系管理员！！！");
            })
        },

    }
}
</script>

<style scoped>
.searchBox {
    margin-left: 20px;
    /* 向右靠 */
    margin-top: 20px;
    /* 向右靠 */
}

.bigBox {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    /* 或使用 center/ flex-end，根据需求 */
    margin-top: 20px;
    /* 向下靠 */
    justify-content: flex-start;
    /* 保证顶部对齐 */
}
</style>